package com.xk._01基础篇._00LeetCode._树;

import java.util.LinkedList;
import java.util.Queue;

/*
 * 226. 翻转二叉树
 * https://leetcode.cn/problems/invert-binary-tree/
 *
 * 给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。
 *
 *      4                      4
 *   2    7      ---->       7    2
 * 1  3  6  9              9  6  3  1
 */
public class Test01_翻转二叉树 {
    // 层序遍历
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        return root;
    }

    // 递归 前序遍历
    public TreeNode invertTree1(TreeNode root) {
        if (root == null) return root;
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree1(root.left);
        invertTree1(root.right);
        return root;
    }

    // 递归 后序遍历
    public TreeNode invertTree2(TreeNode root) {
        if (root == null) return root;

        invertTree2(root.left);
        invertTree2(root.right);
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        return root;
    }

    // 递归 中序遍历 稍微有点不一样
    public TreeNode invertTree3(TreeNode root) {
        if (root == null) return root;

        invertTree3(root.left);
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree3(root.left); // 之前的右子树已经是目前的左子树了
        return root;
    }
}
